package com.hmall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.hmall.common.clients.ItemClient;
import com.hmall.common.constants.MqConstants;
import com.hmall.common.dto.PageDTO;
import com.hmall.search.pojo.ItemDoc;
import com.hmall.search.pojo.PageResult;
import com.hmall.search.pojo.RequestParams;
import com.hmall.search.service.SearchService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;

@Service
@Slf4j
public class SearchServiceImpl implements SearchService {

    @Resource
    RabbitTemplate rabbitTemplate;

    @Resource
    private RestHighLevelClient client;

    @Resource
    private ItemClient itemClient;


    public void sendMessage(String i) {
        // 设置全局唯一的消息ID，需要封装到CorrelationData中
        CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
        // 添加callback
        correlationData.getFuture().addCallback(
                result -> {
                    if (result.isAck()) {
                        // 3.1.ack，消息成功
                        log.debug("消息发送成功, ID:{}", correlationData.getId());
                    } else {
                        // 3.2.nack，消息失败
                        log.error("消息发送失败, ID:{}, 原因{}", correlationData.getId(), result.getReason());
                        //sendMessage(i);
                    }
                },
                ex -> log.error("消息发送异常, ID:{}, 原因{}", correlationData.getId(), ex.getMessage())
        );
        rabbitTemplate.convertAndSend("", MqConstants.ITEM_INSERT_QUEUE, i, correlationData);
    }


    @Override
    public PageDTO<ItemDoc> search(RequestParams params) {
        try {

            //准备请求
            SearchRequest request = new SearchRequest("hmsc");
            //准备查询条件
            buildBasicQuery(params, request);
            //设置分页参数
            int page = params.getPage();
            int size = params.getSize();
            request.source().from((page - 1) * size).size(size);
            //设置排序
            String sort = params.getSortBy();
            if ("sold".equals(sort)) {
                request.source().sort(sort, SortOrder.DESC);
            } else if ("price".equals(sort)) {
                request.source().sort(sort, SortOrder.ASC);
            }
            //设置高亮
            request.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false));
            //发送请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            return handleResponse(response);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private PageDTO<ItemDoc> handleResponse(SearchResponse response) {
        SearchHits searchHits = response.getHits();
        long total = searchHits.getTotalHits().value;
        SearchHit[] hits = searchHits.getHits();
        List<ItemDoc> itemDocs = new ArrayList<>();
        for (SearchHit hit : hits) {
            String json = hit.getSourceAsString();
            ItemDoc itemDoc = JSON.parseObject(json, ItemDoc.class);
            Map<String, HighlightField> map = hit.getHighlightFields();
            if (map != null && map.size() > 0) {
                HighlightField field = map.get("name");
                String value = field.getFragments()[0].string();
                itemDoc.setName(value);
            }
            itemDocs.add(itemDoc);
        }
        return new PageDTO<>(total, itemDocs);
    }

    private void buildBasicQuery(RequestParams params, SearchRequest request) {
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        String key = params.getKey();
        if (key == null || "".equals(key)) {
            boolQuery.must(QueryBuilders.matchAllQuery());
        } else {
            boolQuery.must(QueryBuilders.matchQuery("all", key));
        }
        //分类条件
        if (params.getCategory() != null && !params.getCategory().equals("")) {
            boolQuery.filter(QueryBuilders.termQuery("category", params.getCategory()));
        }
        //品牌条件
        if (params.getBrand() != null && !params.getBrand().equals("")) {
            boolQuery.filter(QueryBuilders.termQuery("brand", params.getBrand()));
        }
        //价格条件
        if (params.getMinPrice() != null && params.getMaxPrice() != null) {
            boolQuery.filter(QueryBuilders
                    .rangeQuery("price")
                    .gte(params.getMinPrice()*100)
                    .lte(params.getMaxPrice()*100));
        }
        //算分函数将广告置顶
        FunctionScoreQueryBuilder queryBuilder = QueryBuilders.functionScoreQuery(
                boolQuery,
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                QueryBuilders.termQuery("isAD", true),
                                ScoreFunctionBuilders.weightFactorFunction(100)
                        )
                }
        );
        request.source().query(queryBuilder);
    }

    @Override
    public List<String> getSuggestion(String prefix) {
        try {
            //发起Request请求
            SearchRequest request = new SearchRequest("hmsc");
            //准备DSL
            request.source().suggest(new SuggestBuilder().addSuggestion(
                    "suggestions",
                    SuggestBuilders.completionSuggestion("suggestion")
                            .prefix(prefix)
                            .skipDuplicates(true)
                            .size(10)
            ));
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //解析结果
            Suggest suggest = response.getSuggest();
            //根据补全查询名称,获取补全结果
            CompletionSuggestion suggestions = suggest.getSuggestion("suggestions");
            //获取optons
            List<CompletionSuggestion.Entry.Option> options = suggestions.getOptions();
            //遍历
            List<String> list = new ArrayList<>(options.size());
            for (CompletionSuggestion.Entry.Option option : options) {
                String text = option.getText().toString();
                list.add(text);
            }
            return list;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 过滤项聚合功能
     *
     * @param params
     * @return
     */
    @Override
    public Map<String, List<String>> filters(RequestParams params) {
        try {
            //准备请求
            SearchRequest request = new SearchRequest("hmsc");
            //准备query
            buildBasicQuery(params, request);
            //设置size
            request.source().size(0);
            //聚合
            buildAggregation(request);
            //发起请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //解析结果
            Map<String, List<String>> map = new HashMap<>();
            Aggregations aggregations = response.getAggregations();
            //获取品牌结果
            List<String> brand_agg = getAggByName(aggregations, "brand_agg");
            map.put("brand", brand_agg);
            //获取分类结果
            List<String> category = getAggByName(aggregations, "category_agg");
            map.put("category", category);
            return map;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private List<String> getAggByName(Aggregations aggregations, String name) {
        Terms brandAgg = aggregations.get(name);
        List<? extends Terms.Bucket> buckets = brandAgg.getBuckets();
        List<String> list = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            String keyAsString = bucket.getKeyAsString();
            list.add(keyAsString);
        }
        return list;
    }

    private void buildAggregation(SearchRequest request) {
        //准备DSL
        request.source().aggregation(AggregationBuilders
                .terms("brand_agg")
                .field("brand")
                .size(20));
        request.source().aggregation(AggregationBuilders
                .terms("category_agg")
                .field("category")
                .size(20));
    }

    /**
     * 商品上架数据同步到ES
     *
     * @param id
     */
    @Override
    public void insertById(Long id) {
        try {
            //0.根据id查出商品数据
            com.hmall.common.dto.Item item = itemClient.findByItemId(id);
            //1.准备Request对象
            IndexRequest request = new IndexRequest("hmsc").id(item.getId().toString());
            //2.准备Json文档
            request.source(JSON.toJSONString(item), XContentType.JSON);
            //3.发送请求
            client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException("系统异常数据同步未成功");
        }


    }

    /**
     * 商品下架从ES中删除
     *
     * @param id
     */
    @Override
    public void deleteById(Long id) {

        try {
            //1.准备Request
            DeleteRequest request = new DeleteRequest("hmsc", id.toString());
            //2.发送请求
            client.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException("系统异常删除");
        }

    }
}
